package com.baidu.web.filter;

import com.baidu.common.bean.User;
import com.baidu.common.exception.WebException;
import com.baidu.service.UserService;
import com.baidu.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: BSS
 * @create: 2020/8/21/8:40
 */
public class LoginFilter implements Filter {
    private UserService userService = new UserServiceImpl();
    private List<String> allowedPath = new ArrayList<>();

    public LoginFilter() throws WebException {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        String contextPath = filterConfig.getServletContext().getContextPath();
        allowedPath.add(contextPath+"/user/login");
        allowedPath.add(contextPath+"/goods/list");
        allowedPath.add(contextPath+"/login.jsp");
        allowedPath.add(contextPath+"/goods/addCar");
        allowedPath.add(contextPath+"/goods/toCar");
        allowedPath.add(contextPath+"/goods/removeCarGoods");
        allowedPath.add(contextPath+"/user/toRegister");
        allowedPath.add(contextPath+"/user/register");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String requestUri = request.getRequestURI();

        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie!=null){
                    String account = cookie.getName();
                    User user = null;
                    try {
                        user = userService.getUserByAccount(account);
                    } catch (WebException e) {
                        e.printStackTrace();
                    }
                    if (user!=null && user.getId()!=null){
                        request.getSession().setAttribute("user",user);
                        filterChain.doFilter(request,response);
                        return;
                    }
                }
            }
        }

        if (allowedPath.contains(requestUri)){
            filterChain.doFilter(request,response);
            return;
        }

        User loginUser = (User) request.getSession().getAttribute("user");

        if (loginUser==null){
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        //do not thing
    }
}
